package com.cango.qutz.web;

import com.cango.framework.base.Constants;
import com.cango.framework.base.controller.BaseController;
import com.cango.framework.base.entity.SessionUserVo;
import com.cango.framework.base.excption.BaseException;
import com.cango.framework.base.util.MD5Util;
import com.cango.qutz.web.auth.menu.service.IMenuService;
import com.cango.qutz.web.auth.position.service.IPositionService;
import com.cango.qutz.web.auth.user.service.ILoginService;
import com.cango.qutz.web.common.SessionUtils;
import com.cango.qutz.web.common.exception.UserNotExistsException;
import com.cango.qutz.web.common.exception.UserOrPasswordEmptyException;
import com.cango.qutz.web.common.exception.UserOrPasswordException;
import com.cango.qutz.web.common.exception.ValidCodeErrorException;
import com.cango.qutz.web.entity.MenuEntity;
import com.cango.qutz.web.util.GlobalConstants;
import com.cango.qutz.web.util.UtilHelper;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户登录相关操作<br>
 * 〈功能详细描述〉
 *
 * @author weih
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
public class LoginController extends BaseController {

    /**
     * cookie中的用户key值
     */
    private static final String USER_KEY_IN_COOKIE = "web_user_key_in_cookie";

    /**
     * 日志对象
     */
    private Log log = LogFactory.getLog(LoginController.class);

    /**
     * 注入登录相关service
     */
    @Autowired
    private ILoginService loginService;

    @Autowired
    IPositionService positionService;

    @Autowired
    private IMenuService menuService;

    @RequestMapping("/loginin")
    public void loginin(String userName, String pwd, String validCode,
                        HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        //返回信息
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
            log.info("用户名或密码为空!");
            throw new UserOrPasswordEmptyException();
        }
        log.info("用户登录操作：用户名【" + userName + "】,登录时间【" + new Date() + "】");
        try {
            if (Constants.IS_VILIDCODE_ENABLE) {
                // 验证码验证
                String rand = (String)session.getAttribute("rand");
                if (UtilHelper.notNull(rand)) {
                    if (!rand.equals(validCode)) {
                        log.info("错误的验证码【" + userName + "】");
                        throw new ValidCodeErrorException();
                    }
                } else {
                    log.info("验证码不存在【" + userName + "】");
                    throw new ValidCodeErrorException();
                }
            }

            SessionUserVo user = loginService.getUserByLoginName(userName);

            if (null == user) {
                log.info("错误的用户名【" + userName + "】");
                throw new UserNotExistsException();
            }else if(!Constants.USER_ADMINISTRATOR_CODE.equals(user.getUserType()) && StringUtils.isEmpty(user.getPositionCode()) ){
                //无岗用户等同无效用户
                throw new UserNotExistsException();
            }
            if (!MD5Util.apr1Crypt(pwd, userName).equals(user.getPassword())) {
                log.info("用户【" + userName + "】输入了错误的密码");
                throw new UserOrPasswordException();
            }

            // 将用户的相关信息写入cookie，按钮权限等不写入cookie
            Gson gson = new Gson();
            //response.addCookie(new Cookie(USER_KEY_IN_COOKIE, gson.toJson(user)));
            response.addCookie(new Cookie(USER_KEY_IN_COOKIE, URLEncoder.encode(gson.toJson(user), "utf-8")));


            SessionUtils.setSessionUser(user);
            resultMap.put("status", GlobalConstants.STATUS_SUCCESS);
        } catch (BaseException e) {
            resultMap.put("status", GlobalConstants.STATUS_FAILURE);
            resultMap.put("errorMsg", e.getMessage());
        } finally {
            super.ajaxJson(response, resultMap);
        }
    }

    /**
     * 功能描述: <br>
     * 登录验证操作
     *
     * @param userName
     * @param pwd
     * @param validCode
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/login")
    public String login(String userName, String pwd, String validCode, Model model,
                        HttpServletResponse response, HttpSession session) {
        return "login";
    }

    /**
     * 功能描述: <br>
     * 登出系统
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/logout")
    public ModelAndView logout() {
        SessionUserVo user = SessionUtils.getSessionUser();
        if (user != null) {
            log.info("User【" + user.getLoginId() + "】 logout system at " + new Date());
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            request.getSession().invalidate();
        }
        return new ModelAndView("login");
    }

    /**
     * 功能描述: <br>
     * 登录成功后跳转首页
     *
     * @param model
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/index")
    public ModelAndView index(Model model) {
        // 得到登录用户
        SessionUserVo user = SessionUtils.getSessionUser();
        log.info("User【" + user.getLoginId() + "】 login system at " + new Date());
        List<Map> list = null;
        if(Constants.USER_ADMINISTRATOR_CODE.equals(user.getUserType())){
            list =  orgAdminMenu();
        }else {
            list = orgMenu(user.getPositionCode());
        }

        model.addAttribute("menuList", list);
        return new ModelAndView("main");
    }

    /**
     * 功能描述: <br>
     * 欢迎页面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/welcome")
    public ModelAndView welcome(Model model) {
        model.addAttribute("companyId",getSessionUser().getCompanyId());
        return new ModelAndView("welcome");
    }

    @RequestMapping("/403")
    public String page403() {
        return "errors/403";
    }

    @RequestMapping("/404")
    public String page404() {
        return "errors/404";
    }

    @RequestMapping("/500")
    public String page500() {
        return "errors/500";
    }

    @RequestMapping("/604")
    public String page604() {
        return "errors/604";
    }

    @RequestMapping("/validImg")
    public String validImg() throws Exception{
        return "validImg";
    }

    private List<Map> orgAdminMenu(){

        // S,超级管理员；A，单一机构管理员；P，应用用户
        /**
         * 超级管理员显示系统管理菜单和超级管理菜单； 机构管理员显示系统管理菜单； 应用用户显示业务菜单；
         */
        List<MenuEntity> menuList = loginService.getAdministratorMenus();
        List<Map> list = new ArrayList<Map>();
        for (MenuEntity menu : menuList) {
            if (menu.getParentCode().equals("0")) {
                Map m = new HashMap();
                m.put("menu", menu);
                m.put("menuCode", menu.getMenuCode());
                m.put("subMenus", new ArrayList<MenuEntity>());
                list.add(m);
            } else {
                for (Map map : list) {
                    if (menu.getParentCode().equals(map.get("menuCode").toString())) {
                        ((List<MenuEntity>) map.get("subMenus")).add(menu);
                    }
                }
            }
        }
 /*       //密码修改
        Map m = new HashMap();
        MenuEntity virtualMenu = new MenuEntity();
        virtualMenu.setMenuCode("is_virtrul_menu");
        virtualMenu.setIcon("glyphicon  glyphicon-cog");
        virtualMenu.setMenuName("密码修改");
        m.put("menu",virtualMenu);
        m.put("menuCode", "is_virtrul_menu");
        List<MenuEntity> subMenus=new ArrayList<MenuEntity>();
        subMenus.add(menuService.queryObjectById("password_change"));
        m.put("subMenus", subMenus);
        list.add(m);*/
        return list;

    }

    /**
     * 功能描述: <br>
     *    重组菜单
     *
     * @param positionCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<Map> orgMenu(String positionCode){
        // S,超级管理员；A，单一机构管理员；P，应用用户
        /**
         * 超级管理员显示系统管理菜单和超级管理菜单； 机构管理员显示系统管理菜单； 应用用户显示业务菜单；
         */
        List<MenuEntity> menuList = loginService.queryMenusByLoginUser(null, positionCode);
        List<Map> list = new ArrayList<>();
        for (MenuEntity menu : menuList) {
            if (menu.getParentCode().equals("0")) {
                Map m = new HashMap();
                m.put("menu", menu);
                m.put("menuCode", menu.getMenuCode());
                m.put("subMenus", new ArrayList<MenuEntity>());
                list.add(m);
            } else {
                for (Map map : list) {
                    if (menu.getParentCode().equals(map.get("menuCode").toString())) {
                        ((List<MenuEntity>) map.get("subMenus")).add(menu);
                    }
                }
            }
        }
        return list;
    }
}
